package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.ReadersService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;


import com.joint.core.entity.manage.Schedule;
import com.joint.core.service.ScheduleService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;


@ParentPackage("manage")
public class AjaxScheduleAction extends BaseFlowAction {
    @Resource
    private ScheduleService scheduleService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private ReadersService readersService;

    /**
     * 日程安排对象(读)
     */
    private Schedule schedule;

    /**
     * 登录人(读)
     */
    private Users loginUser;
    /**
     * 日程类型(读)
     */
    private String type;
    /**
     *  主题
     */
    private String topic;
    /**
     * 开始日期
     */
    private String beginDate;
    /**
     * 结束日期
     */
    private String endDate;
    /**
     * 参与人员
     */
    private String joinUsersId;
    /**
     * 是否公开
     */
    private String open;

    /**
     * 公开范围
     * 1全体员工 2部门 3个人
     */
    private String object;

    /**
     * 公开部门id
     */
    private String openDepartmentId;

    /**
     * 公开个人id
     */
    private String openUsersId;

    /**
     * 具体内容
     */
    private String content;



    /**
     * 项目视图
     * @return
     */
    public String execute(){

        return "schedule";
    }


    /**
     * 日历数据
     * @return
     */
    public String getCalendarJson(){
        pager = new Pager(0);
        pager.setOrderBy("modifyDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
        pager=scheduleService.findByPagerAndLimit(true, "schedule", pager, params);
        List<Schedule> scheduleList;
        if (pager.getTotalCount() > 0){
            scheduleList = (List<Schedule>) pager.getList();
        }else{
            scheduleList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String,Object> rMap;
        for(Schedule schedule: scheduleList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",schedule.getId());
            rMap.put("title",schedule.getTopic());
            rMap.put("start", DataUtil.DateToString(schedule.getBeginDate(), "yyyy-MM-dd HH:mm"));
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        return  ajaxJson(dataRows.toString());


    }



    public String read(){
        loginUser = usersService.getLoginInfo();
        Map<String,Object> rMap = null;
        if(StringUtils.isNotEmpty(keyId)) {
            schedule = scheduleService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
        }
        return "read";
    }

    public String input(){
        loginUser = usersService.getLoginInfo();
        Company company = usersService.getCompanyByUser();
        if (StringUtils.isNotEmpty(keyId)){
            schedule = scheduleService.get(keyId);
        }

        return "input";
    }

    private void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            schedule = scheduleService.get(keyId);
        }else{
            schedule = new Schedule();
            schedule.setCreater(usersService.getLoginInfo());
        }
        schedule.setType(type);
        schedule.setTopic(topic);
        schedule.setBeginDate(DataUtil.StringToDate(beginDate));
        schedule.setEndDate(DataUtil.StringToDate(endDate));
        schedule.setOpen(StringUtils.equals(open, "1") ? true : false);
        schedule.setContent(content);
        List<Users> usersList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(joinUsersId)){
            String[] idArr = joinUsersId.split(",");
            for(String id:idArr){
                usersList.add(usersService.get(id.trim()));
            }
        }
        schedule.setJoinUsers(usersList);
        List<Department> departmentList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(openDepartmentId)){
            String[] idArr = openDepartmentId.split(",");
            for(String id:idArr){
                departmentList.add(departmentService.get(id.trim()));
            }
        }
        List<Users> usersList2 = Lists.newArrayList();
        if(StringUtils.isNotEmpty(openUsersId)){
            String[] idArr = openUsersId.split(",");
            for(String id:idArr){
                usersList2.add(usersService.get(id.trim()));
            }
        }
        schedule.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                scheduleService.update(schedule);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                scheduleService.save(schedule, "schedule", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        Company company = usersService.getCompanyByUser();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        // System.out.println("nextStepApproversId:"+nextStepApproversId);
        Set<Users> usersSet = Sets.newHashSet();
        Map<String, Object> map = new HashMap<String, Object>();

        List<Users> usersList = schedule.getJoinUsers();
        for(Users users:usersList){
            usersSet.add(users);
        }
        if(StringUtils.equals(open, "1")){
            if(StringUtils.equals(object,"1") == true){
                map.put("state", BaseEnum.StateEnum.Enable);
                List<Users> usersList2 = (List<Users>) usersService.findByPagerAndCompany(new Pager(0),null,company,map).getList();
                for(Users users:usersList2){
                    usersSet.add(users);
                }
            }else if(StringUtils.equals(object,"2") == true){
                List<Department> listDept = schedule.getOpenDepartment();
                for(Department department:listDept){
                    List<Duty> dutyList = dutyService.getDutys(department);
                    for(Duty duty:dutyList){
                        usersSet.add(duty.getUsers());
                    }
                }
            }else if(StringUtils.equals(object,"3") == true){
                List<Users> usersList2 = schedule.getOpenUsers();
                for(Users users:usersList2){
                    usersSet.add(users);
                }
            }
        }


        try {
            if (StringUtils.isNotEmpty(keyId)) {
                scheduleService.approve(schedule, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
            } else {
                keyId = scheduleService.commit(schedule, FlowEnum.ProcessState.Finished, "schedule", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        //先删除读者
        readersService.deleteByKeyIdBussinessKey(keyId);
        //增加归档后读者
        for(Users users:usersSet){
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("schedule");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }



    public Schedule getSchedule() {
        return schedule;
    }

    public void setSchedule(Schedule schedule) {
        this.schedule = schedule;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getBeginDate() {
        return beginDate;
    }

    public void setBeginDate(String beginDate) {
        this.beginDate = beginDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public String getJoinUsersId() {
        return joinUsersId;
    }

    public void setJoinUsersId(String joinUsersId) {
        this.joinUsersId = joinUsersId;
    }

    public String getOpen() {
        return open;
    }

    public void setOpen(String open) {
        this.open = open;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getObject() {
        return object;
    }

    public void setObject(String object) {
        this.object = object;
    }

    public String getOpenUsersId() {
        return openUsersId;
    }

    public void setOpenUsersId(String openUsersId) {
        this.openUsersId = openUsersId;
    }

    public String getOpenDepartmentId() {
        return openDepartmentId;
    }

    public void setOpenDepartmentId(String openDepartmentId) {
        this.openDepartmentId = openDepartmentId;
    }
}

